$(document).ready(function () {

    $('#pop-wrapper select').select0();

    $('#pop-wrapper .x-4-move').dragging({
        move: 'both',
        randomPosition: false,
        handler: '.panel-heading'
    });

    /*根据一级类别查询二级类别*/
    $('#pop-wrapper select[name="levelOne"]').off('change').on('change', function () {
        var id = $(this).val();
        var _html = '<option value="">-请选择-</option>';
        if (!id) {
            $('#pop-wrapper select[name="levelTwo"]').html(_html);
            $('#pop-wrapper select[name="levelTwo"]').cLearSelect0();
            $('#pop-wrapper select').select0();
            return;
        }
        ajaxSubmitResponseJSON({
            url: 'category/ajaxLevelTwoListByPid.htm/' + id,
            success: function (data) {
                if (data.status == 0) {
                    var o = data.data;
                    if (o && o.length > 0) {
                        for (var i = 0; i < o.length; i++) {
                            _html += '<option value="' + o[i].id + '">' + o[i].name + '</option>';
                        }
                    }
                    $('#pop-wrapper select[name="levelTwo"]').html(_html);
                    $('#pop-wrapper select').select0();
                }
            }
        });
    });

    $(document).off('click', '#pop-wrapper a.attrVal-node-del')
        .on('click', '#pop-wrapper a.attrVal-node-del', function () {
            $(this).parent().remove();
        });

    $(document).off('click', '#pop-wrapper a.attrVal-node-add')
        .on('click', '#pop-wrapper a.attrVal-node-add', function () {
            var attrName = $('#pop-wrapper [name="name"]').val();
            if(!attrName) {
                tipData({message: '请先选择属性!', status: -1});
                return;
            }

            var _html = '<div>' +
                '   <input type="text" class="form-control controlX" name="val" value="" />' +
                '   <input type="text" class="form-control controlX" name="identifier" value="" style="width:80px;"/>' +
                '   <input type="text" class="form-control controlX" name="alias" value="" style="width:80px;"/>' +
                '   <input type="text" class="form-control controlX" name="seq" value="" style="width:40px;"/>' +
                '   <a class="attrVal-node-del">删除</a>' +
                '</div>';
            $('#pop-wrapper .attrVal-content').append(_html);
        });


    var _validateProcessor = function() {
        var _name = $('#pop-wrapper [name="name"]').val();
        if (!_name) {
            /*$('#pop-wrapper .attrVal-content').find('div').remove();*/
            return;
        }

        var _category = $('#pop-wrapper input:hidden[name="categoryId"]').val();
        if (!_category) _category = '0';

        var _newer = true;
        var _thisId = $('#pop-wrapper input:hidden[name="id"]').val();
        if (_thisId) {
            _newer = false;
        }

        ajaxSubmitResponseJSON({
            url: 'attrParam/ajaxByName.htm/' + _category + '/' + _name,
            success: function (data) {
                if (data.status == 0) {
                    var o = data.data;
                    if (o) {
                        if (_newer) {
                            /*$('#pop-wrapper .attrVal-content').find('div').remove();*/
                            $('#pop-wrapper select').cLearSelect0();
                            tipData({message: '所选属性的属性内容已经存在!', status: -1});
                            return;
                        }
                    }

                    /*var _html = '<a class="attrVal-node-add">增加</a>'+
                     '<div>'+
                     '   <input class="form-control controlX" value="内容名称" style="border:0;color:red;" disabled/>'+
                     '   <input class="form-control controlX" value="对应编码" style="border:0;color:red;" disabled/>'+
                     '</div>';*/
                    var _html = '';
                    if (o) {
                        var paramData = JSON.parse(o.paramData);
                        var _i = 1;
                        for (var i in paramData) {
                            var pd = paramData[i];
                            for (var j in pd.params) {
                                var ps = pd.params[j];
                                _html += '<div>' +
                                    '   <input type="text" class="form-control controlX" name="val" value="' + (ps.k) + '" />' +
                                    '   <input type="text" class="form-control controlX" name="identifier" value="' + (ps.v) + '" style="width:80px;" />' +
                                    '   <input type="text" class="form-control controlX" name="alias" value="' + (ps.s) + '"  style="width:80px;" />' +
                                    '   <input type="text" class="form-control controlX" name="seq" value="' + (_i) + '"  style="width:40px;" />' +
                                    '   <a class="attrVal-node-del">删除</a>' +
                                    '</div>';
                            }
                            _i++;
                        }
                    }
                    if (_html != '') {
                        $('#pop-wrapper .attrVal-content').html(_html);
                    }
                }
            }
        });
    };

    $('#pop-wrapper select[name="levelTwo"]').off('change').on('change', function () {
        /*var _category = $(this).val();
         if (!_category) _category = '0';
         $('#pop-wrapper input:hidden[name="categoryId"]').val(_category);*/

        var levelOne = $('#pop-wrapper [name="levelOne"]').val();
        var levelTwo = $(this).val();
        var levelId = ($.trim(levelTwo).length > 0) ? ($.trim(levelTwo)) : ($.trim(levelOne).length > 0 ? $.trim(levelOne) : '0');
        $('#pop-wrapper input:hidden[name="categoryId"]').val(levelId);

        _validateProcessor();
    });

    $('#pop-wrapper select[name="name"]').off('change').on('change', function () {
        var _name = $(this).val();
        if (!_name) {
            /*$('#pop-wrapper .attrVal-content').find('div').remove();*/
            return;
        }
        /*var _category = $('#pop-wrapper select[name="levelTwo"]').val();
         if (!_category) _category = '0';
         $('#pop-wrapper input:hidden[name="categoryId"]').val(_category);*/

        var levelOne = $('#pop-wrapper [name="levelOne"]').val();
        var levelTwo = $('#pop-wrapper [name="levelTwo"]').val();
        var levelId = ($.trim(levelTwo).length > 0) ? ($.trim(levelTwo)) : ($.trim(levelOne).length > 0 ? $.trim(levelOne) : '0');
        $('#pop-wrapper input:hidden[name="categoryId"]').val(levelId);

        _validateProcessor();
    });

    $('#pop-wrapper .btn-4-save').off('click').on('click', function () {
        var id = $('#pop-wrapper input:hidden[name="id"]').val();
        var url = 'attrParam/add.htm';
        if (id) {
            url = 'attrParam/modify.htm';
        }

        var attrName = $('#pop-wrapper [name="name"]').val();
        if (!attrName) {
            tipData({message: '请先选择属性', status: -1});
            return;
        }

        var levelOne = $('#pop-wrapper [name="levelOne"]').val();
        var levelTwo = $('#pop-wrapper [name="levelTwo"]').val();
        /*if (!levelTwo) {
         levelTwo = '0';
         }
         $('#pop-wrapper input:hidden[name="categoryId"]').val($.trim(levelTwo));*/
        var levelId = ($.trim(levelTwo).length > 0) ? ($.trim(levelTwo)) : ($.trim(levelOne).length > 0 ? $.trim(levelOne) : '0');
        $('#pop-wrapper input:hidden[name="categoryId"]').val(levelId);

        var level = '0';
        if ($.trim(levelOne).length > 0) level = '1';
        if ($.trim(levelTwo).length > 0) level = '2';
        $('#pop-wrapper input:hidden[name="level"]').val(level);

        var params = [];
        var _ps = [];
        var _k = [];
        var _i = [];
        var _a = [];
        var _s = [];
        var abort = false;
        $('#pop-wrapper .attrVal-content').find('input[name="val"]').each(function(){
            var k = $.trim($(this).val());
            if(k == "") {
                $(this).parent().remove();
            }

            if(k.length > 0){
                if (_k.indexOf(k) != -1) {
                    tipData({message: '有相同的内容名称[' + k + ']', status: -1});
                    abort = true;
                    return false;
                }

                var _identifier = $(this).siblings('input[name="identifier"]').val();
                var _alias = $(this).siblings('input[name="alias"]').val();
                var _seq = $(this).siblings('input[name="seq"]').val();
                _seq = $.trim(_seq);
                if (_seq.length > 0) {
                    if (isNaN(_seq)) {
                        tipData({message: '排序值不合法[' + _seq + ']', status: -1});
                        abort = true;
                        return false;
                    }
                    if (_s.indexOf(_seq) != -1) {
                        tipData({message: '请设置不同的排序值[' + _seq + ']', status: -1});
                        abort = true;
                        return false;
                    }
                } else {
                    tipData({message: '请将排序值填写完整', status: -1});
                    abort = true;
                    return false;
                }

                _k.push($.trim(k));
                _i.push($.trim(_identifier));
                _a.push($.trim(_alias));
                _s.push($.trim(_seq));
            }
        });
        if(abort) {
            return;
        }

        var _sorted = _s.slice();
        _sorted.sort(function (a, b) {
            return (a - b);
        });
        for (var x in _sorted) {
            var _idx = _s.indexOf(_sorted[x]);
            _ps.push({
                "k" : _k[_idx],
                "v" : _i[_idx],
                "s" : _a[_idx]
            });
        }

        if(_ps.length > 0){
            params.push({"params":_ps});
            $('#pop-wrapper input:hidden[name="paramData"]').val(JSON.stringify(params));
        } else {
            tipData({message: '请填写属性内容名称及对应编码等信息', status: -1});
            return;
        }

        ajaxSubmitResponseJSON({
            url: url,
            method: 'POST',
            data: $('#pop-wrapper form').serialize(),
            success: function (data) {
                if (data.status == 0) {
                    closeLayer();
                    $('#data-wrapper .btn-4-query').trigger('click');
                }
            }
        });
    });

    $(document).off('keyup', '#pop-wrapper form input[name="val"],' +
        '#pop-wrapper form input[name="identifier"],' +
        '#pop-wrapper form input[name="alias"],' +
        '#pop-wrapper form input[name="seq"]')
        .on('keyup', '#pop-wrapper form input[name="val"],' +
        '#pop-wrapper form input[name="identifier"],' +
        '#pop-wrapper form input[name="alias"],' +
        '#pop-wrapper form input[name="seq"]', function (e) {
            var o = $(this);
            var _name = o.attr('name');
            var _this = o.closest('div');

            switch (e.keyCode) {
                case 13:
                    var _next = _this.next();
                    _next.find('input[name="' + _name + '"]').focus().select();
                    break;
                case 38://↑
                    var _prev = _this.prev();
                    _prev.find('input[name="' + _name + '"]').focus().select();
                    break;
                case 40://↓
                    var _next = _this.next();
                    _next.find('input[name="' + _name + '"]').focus().select();
                    break;
                default:
                    break;
            }
        });

});